const puppeteer = require('puppeteer')
const axios = require('axios')
const fs = require('fs')
const cheerio = require("cheerio")

var currentNumber = 1
const sleep = time => new Promise(resolve => setTimeout(resolve, time))
puppeteer.launch({
    headless: false,
    defaultViewport: {
        width: 1000,
        height: 800
    }
}).then(async browser => {
    const page =await browser.newPage()
    // https://music.163.com/#/discover/playlist/
    const res = await page.goto('https://music.163.com/#/discover/playlist/', {
        waitUntil: 'networkidle0'
    })

    let imgURL = [] 
    let frame = page.frames().find(frame => frame.name() === 'contentFrame')
    async function getImgURL(){
        let imgList = await frame.$$eval(".m-cvrlst li .u-cover img",(imgs) => {
            return imgs.map(item => {
                let src = item.src
                let index = src.indexOf("?")
                return src.slice(0, index)
            })
        })
        return imgList
    }
    
    while(imgURL.length <= 100){
        imgURL = imgURL.concat(await getImgURL())
        await frame.click(".u-page .zbtn.znxt")
        await sleep(2000)
    }

    // if (imgURL.length >= 100){
    //     browser.close()
    //     console.log("All pictures downloaded complete")
    //     return 
    // }else {
    //     imgURL.concat()
    // }

    

    // console.log(imgURL)
    imgURL.forEach(async (e,i) => {
        const res = await axios.get(e, {
            responseType: 'stream'
        })
        await res.data.pipe(fs.createWriteStream(`./pic/${currentNumber}.${e.substr(e.length-3)}`))
        console.log(`已下载图片${currentNumber}张`)
        currentNumber++
        
    })


    // await Promise.all([
    //     page.click(".channel li:nth-child(2) a"),
    //     // page.waitForNavigation()
    // ])


    await sleep(3000)
    await browser.close()
})





// let imgURL = await page.evaluate(imgList =>{
    //     console.log(imgList)
    //     let $ = cheerio.load(document.documentElement)
    //     let imgURL = []
    //     let selector = 'img.j-flag'
    //     let imgUrlList = Array.prototype.slice.call(document.querySelectorAll(selector));
    //     imgUrlList.forEach(e =>{
    //         imgURL.push(e.src)
    //     })
    //     console.log($)
    //     return imgURL
    // }, imgList)




// 加载iframe树
// dumpFrameTree(page.mainFrame(), '')
// function dumpFrameTree(frame, indent){
//     console.log(indent + frame.name() + frame.url());
//     for(let child of frame.childFrames()){
//         dumpFrameTree(child, indent + '  ')
//     }
// }

// const $ = cheerio.load(await frame.content())
    // $(".m-cvrlst li .u-cover img").each(function(){
    //     console.log($(this).attr("src"))
    // })